package cn.xuchunh.sword;

/**
 * Created by XuChunH on 2016/9/18.
 */
public class BTreeSerialize {

    private int index;

    public String Serialize(TreeNode root) {
        if(root == null) {
            return "#,";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(root.val + ",");
        sb.append(Serialize(root.left));
        sb.append(Serialize(root.right));
        return sb.toString();
    }
    public TreeNode Deserialize(String str) {
        if(str == null || str.trim().isEmpty() || "#,".equals(str)){
            return null;
        }
        index = -1;
        return transform(str.split(","));
    }

    private TreeNode transform(String[] seq){
        index++;
        TreeNode node = null;
        if(!"#".equals(seq[index])) {
            node = new TreeNode(Integer.valueOf(seq[index]));
            node.left = transform(seq);
            node.right = transform(seq);
        }
        return node;
    }

}
